package com.adgox.tiantianbiting.redpacket.share.share_detail;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.TtbtApplication;
import com.adgox.tiantianbiting.adapter.ShareDetailAdapter;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.ProgramDetailBean;
import com.adgox.tiantianbiting.bean.ShareDetailBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.TimeUtils;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShareDetailActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.iv_book)
    ImageView ivBook;
    @BindView(R.id.tv_listen)
    TextView tvListen;
    @BindView(R.id.tv_season)
    TextView tvSeason;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.share_avatar1)
    ImageView shareAvatar1;
    @BindView(R.id.share_name1)
    TextView shareName1;
    @BindView(R.id.share_avatar2)
    ImageView shareAvatar2;
    @BindView(R.id.share_name2)
    TextView shareName2;
    @BindView(R.id.share_avatar3)
    ImageView shareAvatar3;
    @BindView(R.id.share_name3)
    TextView shareName3;
    @BindView(R.id.tv_invite)
    TextView tvInvite;
    @BindView(R.id.tv_haisheng)
    TextView tvHaisheng;
    @BindView(R.id.tv_left_time)
    TextView tvLeftTime;
    @BindView(R.id.tv_jieshu)
    TextView tvJieshu;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.tv_book_name)
    TextView tvBookName;
    @BindView(R.id.tv_describe)
    TextView tvDescribe;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.tv_last_price)
    TextView tvLastPrice;
    @BindView(R.id.ll_share)
    LinearLayout llShare;

    private int programId;
    private UserInfo user;
    private long shareCreateTime;
    private long survivalTime;
    private CountDownTimer countDownTimer;
    private String shareStatus;
    private Dialog shareDialog;
    private ShareDetailBean bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_detail);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        programId = intent.getIntExtra("programId", -1);
        if (programId <= 0) {
            Toast.makeText(this, "获取节目信息失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        init();
    }

    private void init() {
        user = SessionManager.getDefault().getUser();
        OkGo.<BaseResponseBean<ShareDetailBean>>get(ApiConstant.BASE_URL + ApiConstant.GET_SHARE_DETAIL + programId + "/" +
                user.getId() + "/" + user.getId())
                .execute(new JsonCallback<BaseResponseBean<ShareDetailBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<ShareDetailBean>> response) {
                        if (!"0".equals(response.body().getCode()) || response.body().getData() == null) {
                            Toast.makeText(ShareDetailActivity.this, "获取节目信息失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        setData(response.body().getData());
                    }
                });

        OkGo.<BaseResponseBean<PageBean<ProgramDetailBean>>>get(ApiConstant.BASE_URL + ApiConstant.SHARE_FOR_FREE_PROGRAM_LIST)
                .params("startPoint", 1)
                .params("maxPage", 10)
                .execute(new JsonCallback<BaseResponseBean<PageBean<ProgramDetailBean>>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<PageBean<ProgramDetailBean>>> response) {
                        if ("0".equals(response.body().getCode()) && response.body().getData() != null) {
                            LinearLayoutManager layoutManager = new LinearLayoutManager(ShareDetailActivity.this);
                            rv.setLayoutManager(layoutManager);
                            ShareDetailAdapter adapter = new ShareDetailAdapter(response.body().getData().getData());
                            rv.setAdapter(adapter);
                        }
                    }
                });
    }

    private void setData(ShareDetailBean data) {
        ArrayList<ImageView> imageViews = new ArrayList<>();
        imageViews.add(shareAvatar1);
        imageViews.add(shareAvatar2);
        imageViews.add(shareAvatar3);

        ArrayList<TextView> textViews = new ArrayList<>();
        textViews.add(shareName1);
        textViews.add(shareName2);
        textViews.add(shareName3);

        bean = data;
        Glide.with(this).load(data.getShareImageUrl()).into(ivBook);
        tvBookName.setText(data.getTitle());
        tvDescribe.setText(data.getDescribe());
        tvListen.setText(data.getListenNum() + "");
        tvSeason.setText(data.getTotalSeason() + "集");
        tvLastPrice.setText(data.getTotalCount() + "听币");
        List<UserInfo> shareUsers = data.getShareUsers();
        for (int i = 0; i < shareUsers.size(); i++) {
            Glide.with(this).load(shareUsers.get(i).getWxAvatarUrl()).into(imageViews.get(i));
            textViews.get(i).setText(shareUsers.get(i).getWxNickname());
            tvHaisheng.setVisibility(View.VISIBLE);
            tvJieshu.setVisibility(View.VISIBLE);
            shareCreateTime = data.getShareCreateTime();
            survivalTime = data.getSurvivalTime();
        }
        shareStatus = data.getShareStatus();
        if ("0".equals(shareStatus)) {
            //分享成功

        } else if ("1".equals(shareStatus)) {
            //分享中
            tvTips.setText("还差" + (3 - shareUsers.size()) + "个助力就可以免费领课程, 快去求助哦!");
            tvInvite.setBackgroundResource(R.drawable.bg_btn_try_listen);
            long time = data.getShareCreateTime() + data.getSurvivalTime() - System.currentTimeMillis();
            countDownTimer = new CountDownTimer(time, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int second = (int) (millisUntilFinished / 1000);
                    tvLeftTime.setText(TimeUtils.SecondToHms(second) + "");
                }

                @Override
                public void onFinish() {
                    llShare.setVisibility(View.INVISIBLE);
                    shareStatus = "2";
                }
            }.start();
        } else if ("2".equals(shareStatus)) {
            //分享失败
            tvTips.setText("非常抱歉, 由于没集齐小伙伴, 本次分享失败了");
            tvInvite.setBackgroundColor(Color.parseColor("#dfdfdf"));
            tvInvite.setText("分享失败");
            llShare.setVisibility(View.INVISIBLE);
        }
    }

//    Handler handler = new Handler();
//    Runnable runnable = new Runnable() {
//        @Override
//        public void run() {
//            long leftTime = shareCreateTime + survivalTime - System.currentTimeMillis();
//            if (leftTime > 0) {
//                tvLeftTime.setText(TimeUtils.MstoHMS(leftTime));
//                handler.postDelayed(runnable, 1000);
//            } else {
//
//            }
//        }
//    };

    @OnClick(R.id.img_finish)
    public void onFinishClicked() {
        finish();
    }

    @OnClick(R.id.tv_invite)
    public void onInviteClicked() {
        if ("0".equals(shareStatus)) {

        } else if ("1".equals(shareStatus)) {
            toShare();
        }
    }

    private void toShare() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_share, null);

        shareDialog = new Dialog(this, R.style.TransparentDialog);
        shareDialog.setContentView(view);
        LinearLayout llWX = shareDialog.findViewById(R.id.ll_wx);
        LinearLayout llWXMoments = shareDialog.findViewById(R.id.ll_wx_moments);
        TextView tvCancel = shareDialog.findViewById(R.id.tv_cancel);

        llWX.setOnClickListener(this);
        llWXMoments.setOnClickListener(this);
        tvCancel.setOnClickListener(this);

        Window window = shareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

        shareDialog.setCanceledOnTouchOutside(false);
        shareDialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_wx:
                shareToWx();
                shareDialog.dismiss();
                break;
            case R.id.ll_wx_moments:
                shareToWxMoments();
                shareDialog.dismiss();
                break;
            case R.id.tv_cancel:
                if (shareDialog != null) shareDialog.dismiss();
                break;
        }
    }

    private void shareToWxMoments() {
        SendMessageToWX.Req req = SharePre();
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        TtbtApplication.wxapi.sendReq(req);
    }

    private void shareToWx() {
        SendMessageToWX.Req req = SharePre();
        req.scene = SendMessageToWX.Req.WXSceneSession;
        TtbtApplication.wxapi.sendReq(req);
    }

    private SendMessageToWX.Req SharePre() {
        if (!isWXAppInstall()) return null;


        int programId = bean.getId();
        //记录分享记录
//        addShareRecord(programId, userId);

        WXWebpageObject webPage = new WXWebpageObject();
        String url = "https://blistening.cn/ttbt_act_h5/share-detail.html"
                + "?programId=" + programId + "&srcUserId=" + user.getId();
        webPage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage();
        msg.title = bean.getTitle();
        msg.description = bean.getDescribe();
        msg.mediaObject = webPage;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webPage");
        req.message = msg;
        return req;
    }

    private String buildTransaction(String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();

    }

    private boolean isWXAppInstall() {
        if (TtbtApplication.wxapi.isWXAppInstalled()) {
            return true;
        } else {
            Toast.makeText(this, "请安装微信客户端", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}
